package com.sc.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sc.admin.common.constant.StringPools;
import com.sc.admin.common.enums.ModuleEnum;
import com.sc.admin.common.util.ObjUtils;
import com.sc.admin.converter.OperLogConverter;
import com.sc.admin.mapper.sys.SysOperLogMapper;
import com.sc.admin.model.entity.sys.SysOperLog;
import com.sc.admin.model.query.SysOperLogQuery;
import com.sc.admin.model.vo.SysLogExportVO;
import com.sc.admin.model.vo.SysOperLogVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @description: 系统日志业务层
 */
@Service
@RequiredArgsConstructor
public class SysLogService extends ServiceImpl<SysOperLogMapper, SysOperLog> {
    private final OperLogConverter operLogConverter;

    private static LambdaQueryWrapper<SysOperLog> getWrapper(SysOperLogQuery query) {
        return new LambdaQueryWrapper<SysOperLog>()
                .eq(!ObjectUtils.isEmpty(query.getId()), SysOperLog::getId, query.getId())
                .eq(!ObjectUtils.isEmpty(query.getStatus()), SysOperLog::getStatus, query.getStatus())
                .eq(StringUtils.isNotBlank(query.getBusinessType()), SysOperLog::getBusinessType, query.getBusinessType())
                .like(StringUtils.isNotBlank(query.getCreateBy()), SysOperLog::getOperName, query.getCreateBy())
                .like(StringUtils.isNotBlank(query.getModule()), SysOperLog::getModule, query.getModule())
                .ge(!ObjectUtils.isEmpty(query.getBeginTime()), SysOperLog::getOperTime, query.getBeginTime())
                .le(!ObjectUtils.isEmpty(query.getEndTime()), SysOperLog::getOperTime, query.getEndTime())
                .orderByDesc(SysOperLog::getOperTime);
    }

    public IPage<SysOperLogVO> pageLog(SysOperLogQuery query) {

        LambdaQueryWrapper<SysOperLog> wrapper = getWrapper(query);

        Page<SysOperLog> page = page(new Page<>(query.getPageNum(), query.getPageSize()), wrapper);
        return operLogConverter.toPageVo(page);
    }

    public List<SysLogExportVO> listExportLogs(SysOperLogQuery queryParams) {

        return list(getWrapper(queryParams))
                .stream().map(obj ->
                        ObjUtils.copy(obj, SysLogExportVO.class)
                                .setStatus(ObjUtils.equals(obj.getStatus(), 0) ? StringPools.SUCCESS_ZH : StringPools.ERROR_ZH)
                                .setModule(ModuleEnum.getName(obj.getModule()))
                ).collect(Collectors.toList());
    }
}
